package client;

import java.io.*;
import java.net.*;
import java.util.*;

import msgs.*;
/**
 * Just sends objects to the server
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class ServerSender extends Thread implements TTConstants {
	private Socket sock;
	private static boolean go;
	
	/**
	 * The outgoing message queue TO the server
	 */
	protected static Vector<ClientMsg> outQ;
	
	private ClientMsg cmsg;
	private ObjectOutputStream oos;
	private int port;
	
	/**
	 * Constructs a serversender on the requester port
	 * @param p1 Port to send on
	 */
	public ServerSender ( int p1 ) {
		outQ = new Vector<ClientMsg>();
		go = true;
		this.port = p1;
	}
	public void run() {
		while (go) {
			// only process if we have something to do
			if (!(outQ.isEmpty())) {
				cmsg = outQ.remove(0);
				try {
					sock = new Socket(TTClient.server, port);
					oos = new ObjectOutputStream(sock.getOutputStream());
					oos.writeObject(cmsg);
					oos.flush();
					oos.close();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			else {
				// nothing to do, sleep a moment so we dont kill cpu
				try { Thread.sleep(100); }
				catch(InterruptedException e) {}
			}
		}
		
		try {
			oos.close();
			sock.close();
		}
		catch(Exception e) {}
	}
	
	/**
	 * Cleanly shuts down the server Sender
	 */
	public static void killServerSender() {
		while (go) {
			if (outQ.isEmpty()) go = false;
			else try {
				Thread.sleep(10);
			} 
			catch (Exception e) {}
		}
	}
}
